#include "udpsever.h"
#include <QDateTime>
#include <QDataStream>
#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>
#include <sys/time.h>
#include "shared/common.h"

UDPSever::UDPSever(quint16 port, QObject* parent)
: QThread(parent), _port(port)
{
}

void UDPSever::run()
{
    _UDPServer = new QUdpSocket();
    _UDPServer->bind(_port,QUdpSocket::ShareAddress);
    tiempo=0;

    if (!_UDPServer->isValid()) {
        return;
    }
    _log->LogIt(tr("UDP Server ON"));
    processPendingDatagrams();
    exec();
 }

void UDPSever::processPendingDatagrams()
{
        while (_UDPServer->waitForReadyRead(-1)) {
            while (_UDPServer->hasPendingDatagrams()) {
                QByteArray datagram;
                datagram.resize(_UDPServer->pendingDatagramSize());
                QHostAddress sender;
                quint16 senderPort;

                _UDPServer->readDatagram(datagram.data(), datagram.size(),&sender,&senderPort);
                Packets::TLPacket pkt(datagram);

                QByteArray buffer;
                QString sbuf;
                quint8 number = (*datagram.data());

                if(DEBUG_UDP_RECV && FILTER_UDP((quint16)number))
                   _log->LogIt(pkt.StDump(),Logg::IDEBUD);
                quint32  pid = 0;
                QBuffer dev(&datagram);
                dev.open(QBuffer::ReadWrite);
                QDataStream stm(&dev);

                switch (number)
                {
                    case 0x1:
                        sbuf="00 00 00 00 00 00 00 00 01 00 00 00 00";
                        sbuf="04 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00";
                        _UDPServer->writeDatagram(buffer,sender,senderPort);
                        /*buffer = QByteArray::fromHex(sbuf.toAscii());

                        tiempo++;
                         val = tiempo;//QDateTime::currentDateTime().toTime_t()+tiempo;
                         //_clients.insert(val,tiempo);
                         //sbuf+=gettick(val);
                        theping=sends[tiempo];
                        SWAP(theping);
                        sbuf+=gettick(theping);
                        sbuf+="00";
                        tiempo++;
                        if(tiempo >32)
                            tiempo=0;
                        */
                        break;

                    case 0x84:
                        //sbuf="84 00 00 00 00 00 00 00 02 00 00 00 00 04 60 c1 61";
                        /* stm= pkt.getStream();
                        (*stm).device()->seek((*stm).device()->size()-4);
                        (*stm) >> val;
                        sbuf="04 00 00 00 00 00 00 00 01 00 00 00 00";
                        theping=sends[tiempo];
                        SWAP(theping);
                        sbuf+=gettick(theping);
                        sbuf+="00";
                        tiempo++;
                        if(tiempo >32)
                            tiempo=0;*/
                        break;

                    case 0x2:
                        sbuf="00 00 00 00 00 00 00 00 02 00 00 00 00";

                        if(datagram.size() == 20){
                            stm.device()->seek(datagram.size()-4);
                            stm >> pid;
                        }else if(pkt.GetRaw()->size() > 31){
                            stm.device()->seek(datagram.size()-8);
                            stm >> pid;
                        }
                        if(LPlayers.contains(pid))
                        {
                            LPlayers[pid]->setUDPort(senderPort);
                        }
                        break;

                    case 0x4:
                        /*sbuf="84 00 00 00 00 00 00 00 04 00 00 00 00";
                        stm = pkt.getStream();
                        (*stm).device()->seek((*stm).device()->size()-4);
                        (*stm) >> val;
                        sbuf+=gettick(val);*/
                        break;

                    case 0x51:
                      //sbuf="81 00 00 00 02 00 00 00 02 00 00 00 00";
                        break;

                    case 0x81:
                        //sbuf="81 00 00 00 02 00 00 00 02 00 00 00 00";
                        break;

                    case 0x08:
                        sbuf="00 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00 00 00";
                        break;

                    default:
                        break;
                }
                 buffer = QByteArray::fromHex(sbuf.toAscii());
                 if(!buffer.isEmpty())
                 {
                     QWaitCondition sleep;
                     sleep.wait(&mutex,1);

                    _UDPServer->writeDatagram(buffer,sender,senderPort);
                    quint8 cmd =(*buffer.data());
                    if(DEBUG_UDP_SEND && FILTER_UDP((quint16)cmd))
                            _log->LogIt(pkt.StDump(buffer),Logg::ODEBUD);
                 }
            }
        }
}

QString UDPSever::gettick(quint32 val)
{
    std::stringstream text;
     text << setfill('0') << setw(8) << hex << ( int ) val ;
    QString hexa(text.str().c_str());
/*    hexa.setNum(val,16);
    if(hexa.count() % 2 !=0)
        hexa="0"+hexa;*/
    return hexa;
}
